<?php

namespace app\logic;

use app\components\helpers\MappingHelper;
use app\components\helpers\ToolsHelper;
use app\components\helpers\TreeHelper;
use app\forms\MenuForm;
use app\models\Item;
use app\models\Menu;
use app\models\Role;
use app\models\RoleItem;
use yii\db\StaleObjectException;
use yii\web\HttpException;

/**
 * 菜单逻辑类
 */
class MenuLogic extends BaseLogic
{
    /**
     * Notes:菜单列表
     * Date: 2020/7/22
     * Time: 10:47
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getList($param)
    {
        $form = static::_validate(new MenuForm(), $param, 'index');
        $where = [
            'select' => ['id', 'parent_id as parentId', 'name', 'level', 'status', 'type', 'target', 'route', 'path'],
            'orderBy' => 'sort ASC',
        ];
        if ($form['name']) {
            $where['where'] = ['like', 'name', $form['name']];
        }
        $menu = Menu::getList($where);
        if ($menu) {
            foreach ($menu as &$value) {
                $value['type'] = Menu::showTypeText($value['type']);
                $value['target'] = Menu::showTargetText($value['target']);
            }
        }
        $resp['typeList'] = Menu::getTypeMapping();
        $resp['statusList'] = MappingHelper::statusList();
        $resp['targetList'] = Menu::getTargetMapping();
        $resp['menu'] = TreeHelper::format($menu);
        return $resp;
    }

    /**
     * 创建菜单（ 接收表单数据 ）
     * @param $param
     * @throws HttpException
     */
    public static function create($param)
    {
        $form = static::_validate(new MenuForm(), $param, 'create');
        $attr = $form->getAttributes();
        $attr['parent_id'] = $form['parentId'];
        $attr['item_id'] = $form['itemId'];
        Menu::newCreate($attr);
        throw new HttpException(200, 'OK');
    }

    /**
     * 编辑菜单（ 接收表单数据 ）
     * @param $param
     * @throws HttpException
     */
    public static function update($param)
    {
        $form = static::_validate(new MenuForm(), $param, 'update');
        $attr = $form->getAttributes();
        $id = $form['id'];
        $attr['parent_id'] = $form['parentId'];
        $attr['item_id'] = $form['itemId'];
        unset($attr['parentId'], $attr['itemId'], $attr['id'], $attr['q']);
        Menu::updateByPk($attr, $id);
        Item::updateByPk(['status' => $attr['status']], $attr['item_id']);
        self::_updateChildren(['id' => $id, 'status' => $attr['status']]);
        throw new HttpException(200, 'OK');
    }

    /**
     * Notes:更新菜单的子权限模块
     * Date: 2020/7/24
     * Time: 13:58
     * @param $params
     */
    public static function _updateChildren($params)
    {
        $children = Menu::getList([
            'select' => ['id', 'item_id'],
            'where' => ['like', 'path', $params['id'] . '%', false]
        ]);
        if ($children) {
            $menuId = array_column($children, 'id');
            $itemId = array_column($children, 'item_id');
            Menu::updateDataById(['status' => $params['status']], $menuId);
            Item::updateDataById(['status' => $params['status']], $itemId);
        }
    }

    /**
     * 删除菜单
     * @param $param
     * @throws \Throwable
     * @throws StaleObjectException
     */
    public static function delete($param)
    {
        $form = static::_validate(new MenuForm(), $param, 'delete');
        $menu = Menu::findDataById($form['id']);
        $children = Menu::getList(['where' => ['parent_id' => $form['id']], 'count' => 'id']);
        if ($children > 0) {
            throw new HttpException(423);
        }
        $del = Menu::realDeleteById($form['id']);
        throw new HttpException(200, 'OK');
    }

    /**
     * Notes:修改菜单状态
     * Date: 2020/7/22
     * Time: 15:31
     * @param $param
     * @throws HttpException
     */
    public static function status($param)
    {
        $form = static::_validate(new MenuForm(), $param, 'status');
        $menu = Menu::findDataById($form['id']);
        Menu::updateByPk(['status' => $form['status']], $form['id']);
        Item::updateByPk(['status' => $form['status']], $menu['item_id']);
        self::_updateChildren(['id' => $form['id'], 'status' => $form['status']]);
        throw new HttpException(200, 'OK');
    }

    /**
     * Notes:菜单详情
     * Date: 2020/7/22
     * Time: 16:54
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function view($param)
    {
        $form = static::_validate(new MenuForm(), $param, 'view');
        $menu = Menu::getSingleByPk($form['id'],
            [
                'id',
                'parent_id as parentId',
                'item_id as itemId',
                'name',
                'level',
                'status',
                'type',
                'target',
                'route',
                'remark'
            ]);
        $roleId = RoleItem::getList(['select' => ['role_id'], 'where' => ['item_id' => $menu['itemId']]]);
        $role = [];
        if ($roleId) {
            $roleId = array_column($roleId, 'role_id');
            $where = [
                'select' => [
                    'r.id',
                    'r.name as roleName',
                    'r.remark',
                    'r.created_at as createdAt',
                    'u.username as userName'
                ],
                'where' => ['in', 'id', $roleId],
                'User' => 1,
            ];
            $role = Role::getJoinList($where);
            if ($role) {
                foreach ($role as &$value) {
                    $value['createdAt'] = ToolsHelper::dateFormat($value['createdAt']);
                    $value['menuName'] = $menu['name'];
                }
            }
        }
        $menu['typeText'] = Menu::showTypeText($menu['type']);
        $menu['targetText'] = Menu::showTargetText($menu['target']);
        $resp['menu'] = $menu;
        $resp['role'] = $role;
        return $resp;
    }

    /**
     * Notes:表单信息
     * Date: 2020/7/22
     * Time: 16:54
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getParam($param)
    {
        $where = ['select' => ['id', 'parent_id AS parentId', 'name']];
        $list = Menu::getList($where);
        return TreeHelper::format($list);
    }

    /**
     * Notes:获取权限列表
     * Date: 2020/7/22
     * Time: 16:54
     * @return array
     * @throws HttpException
     */
    public static function getItem()
    {
        $list = Item::getList(['select' => ['id', 'parent_id as parentId', 'name', 'status']]);
        $menu = Menu::getList(['select' => ['item_id']]);
        if ($menu) {
            $ids = array_column($menu, 'item_id');
            foreach ($list as &$value) {
                if (in_array($value['id'], $ids)) {
                    $value['status'] = Item::DATA_AUTH_YES;
                }
            }
        }
        return TreeHelper::format($list);
    }
}